import { _decorator, CCFloat, Component, EventTouch, instantiate, Node, Prefab, Sprite, SpriteFrame, tween, v3 } from 'cc';
import { FrameAnim } from './FrameAnim';
const { ccclass, property } = _decorator;

enum PLAYER_STAT {
    LIVE = 0,
    DEAD = 1,
    // 无敌
    INVINCIBLE = 2
}

@ccclass('Plane')
export class Plane extends Component {

    bombAnim: SpriteFrame[]

    @property(CCFloat)
    bombTime: number = 0.1;

    @property(SpriteFrame)
    planeIdle: SpriteFrame

    // 子弹Prefab
    @property(Prefab)
    bulletPrefab: Prefab

    private animNode: Node

    private frameAnim: FrameAnim

    private state: PLAYER_STAT

    private bulletsNode: Node

    onLoad(): void {
        this.animNode = this.node.getChildByName("anim")
        this.frameAnim = this.animNode.addComponent(FrameAnim)

        // 触摸移动事件
        this.node.on(Node.EventType.TOUCH_MOVE, (event: EventTouch) => {
            let offset = event.getDelta()
            this.node.setPosition(this.node.getPosition().add3f(offset.x, offset.y, 0))
        }, this)
        this.state = PLAYER_STAT.LIVE

        this.bulletsNode = this.node.parent.getChildByName("Bullets")

        this.schedule(this.shoot.bind(this), 0.2)
    }

    // 射击
    shoot() {
        if (this.state == PLAYER_STAT.DEAD) {
            return;
        }
        let bullet = instantiate(this.bulletPrefab)
        // this.node.parent.addChild(bullet)
        this.bulletsNode.addChild(bullet)
        bullet.setPosition(this.node.getPosition())
        // bullet.setSiblingIndex(9)
      
    }

    // 重生
    reborn() {
        this.animNode.setScale(v3(0, 0, 1))
        this.scheduleOnce(() => {
            this.animNode.setScale(v3(1, 1, 1))
            // 表示是无敌
            this.state = PLAYER_STAT.INVINCIBLE
            this.animNode.getComponent(Sprite).spriteFrame = this.planeIdle;
            tween(this.node).sequence(
                tween().to(0.1, { opacity: 128 }),
                tween().to(0.1, { opacity: 255 })
            ).repeatForever().start()
        }, 1);

        this.scheduleOnce(function () {
            // 完全的出来，可以检测碰撞
            this.state = PLAYER_STAT.LIVE;
            this.animNode.opacity = 255;
            this.node.stopAllActions()
        }.bind(this), 3);
    }

    // 被击中
    onHurt() {
        if (this.state != PLAYER_STAT.LIVE) {
            return;
        }
        this.state = PLAYER_STAT.DEAD;
        // 爆炸效果
        this.frameAnim.spriteFrames = this.bombAnim;
        this.frameAnim.duration = this.bombTime;
        this.frameAnim.playOnce(() => {
            this.reborn()
        });
    }

}

